package com.jari.lg.service.analysis.cross;

import com.jari.lg.domain.*;
import com.jari.lg.mapper.*;
import com.jari.lg.service.analysis.detector.DetectorService;
import com.jari.lg.utils.BaseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CrossService {

    @Autowired
    private DevBaseMapper devBaseMapper;
    @Autowired
    private CrossBaseMapper crossBaseMapper;
    @Autowired
    private ExampleTableMapper exampleTableMapper;
    @Autowired
    private CrossDeviceDataHisMapper crossDeviceDataHisMapper;
    @Autowired
    private CrossRunningStateRtMapper crossRunningStateRtMapper;
    @Autowired
    private CrossJamTimeHisHourMapper crossJamTimeHisHourMapper;
    @Autowired
    private CrossJamTimeHisDayMapper crossJamTimeHisDayMapper;
    @Autowired
    private CrossJamTimeHisMonthMapper crossJamTimeHisMonthMapper;

    private double vehLen = 5.0;  // 车长，米
    private int interval = 5;  // crossrunningstate_rt计算间隔，分钟
    
    @Scheduled(cron = "0 * * * * ?")
    public void addExampleData() {
        //1.利用 Example 对象创建查询条件Criteria
        DevBaseExample example = new DevBaseExample();
        DevBaseExample.Criteria criteria = example.createCriteria();
        //2.将查询条件写入
        criteria.andAreacodeEqualTo("5001");
        //3.进行查询，期间进行各种业务的运算
        List<DevBase> devBaseList = devBaseMapper.selectByExample(example);
        List<DevBase> checkpointList = devBaseList.stream()
                .filter(x -> x.getDevicetype() == "01").collect(Collectors.toList());
        List<CrossBase> crossBaseList = crossBaseMapper.selectByExample(null);
        //4.批量写入结果表,其中insertBatch为用户自定义的函数，需要在Mapper类中声明，在对用的xml文件中定义相应的sql
        List<ExampleTable> exampleTableList = new ArrayList<>();
        ExampleTable ex = new ExampleTable();
        ex.setId("1");
        ex.setName("1");
        ex.setCreatetime(new Date());
        exampleTableList.add(ex);
        exampleTableMapper.insert(ex);
    }


    // 创建2021年全年crossdevicedata_his数据，统计间隔：每小时
    public void createCrossDeviceDataHis2(LocalDateTime start, LocalDateTime last) {
        String crossCode = "crossCode";
        String deviceType = "deviceType";
        String deviceNum = "deviceNum";
        List<Map<String ,String >> crossDevNum = devBaseMapper.getCrossDevNum();
        while (start.isBefore(last)) {
            List<CrossDeviceDataHis> crossDeviceDataHisList = new ArrayList<>();
            for (Map cross:crossDevNum) {
                CrossDeviceDataHis result = new CrossDeviceDataHis();
                result.setUuid(UUID.randomUUID().toString());
                result.setCrossid((String)cross.get(crossCode));
                result.setCrossname(null);
                switch ((String)cross.get(deviceType)) {
                    case "01": // 卡口
                        result.setDevicetype("卡口");
                        result.setDatatype("卡口数据类型");
                        break;
                    case "02": // 电警
                        result.setDevicetype("电警");
                        result.setDatatype("违法数据类型");
                        break;
                    case "03": // 视频检测器
                        result.setDevicetype("视频检测器");
                        result.setDatatype("检测器流量类型");
                        break;
                    case "04": // 诱导屏
                        result.setDevicetype("诱导屏");
                        result.setDatatype("停车诱导数据类型");
                        break;
                    default:
                        result.setDevicetype("其他");
                        result.setDatatype("其他");
                        break;
                }
                int volume_raw = (int)(DetectorService.createDataInRange(2100, 1500) * ((Number)cross.get(deviceNum)).intValue());
                double percentage = DetectorService.createDataInRange(0.99, 0.85);
                int volume_clean = (int)(volume_raw * percentage);
                result.setOriginaldatacount(volume_raw);
                result.setCleandatacount(volume_clean);
                result.setDatestamp(start);
                result.setCreator(null);
                result.setGmtcreate(LocalDateTime.now());
                result.setModifier(null);
                result.setGmtmodified(null);
                result.setDatastatus(null);
                result.setVersion(null);
                result.setRemark(null);
                crossDeviceDataHisList.add(result);
            }
            crossDeviceDataHisMapper.insertBatch(crossDeviceDataHisList);
            start = start.plusHours(1);
        }
    }

    // 创建2022年2月拥堵时长数据，统计间隔：小时
    public void createCrossJamTimeHisHourData2(LocalDateTime start, LocalDateTime last) {
        while (start.isBefore(last)) {
            List<CrossJamTimeHisHour> resultList = new ArrayList();
            for (CrossBase node: BaseData.crossBaseList) {
                String crossType = node.getCrosstype();
                if (crossType.equals("6")  || crossType.equals("7") || crossType.equals("5")){
                    continue;
                }
                CrossJamTimeHisHour result = new CrossJamTimeHisHour();
                result.setCrossid(node.getCrosscode());
                result.setCrossname(node.getCrossname());
                int congDuration = (int)DetectorService.createDataInRange(20, 0);  // 分钟
                result.setTime(congDuration);
                result.setDatetime(start);
                result.setGmtcreate(LocalDate.now());
                resultList.add(result);
            }
            crossJamTimeHisHourMapper.insertBatch(resultList);
            start = start.plusHours(1);
        }
    }

    // 创建2022年2月份每天的拥堵时长，统计间隔：天
    public void createCrossJamTimeHisDayData2(LocalDate start, LocalDate last) {
        while (start.isBefore(last)) {
            List<CrossJamTimeHisDay> resultList = new ArrayList();
            for (CrossBase node : BaseData.crossBaseList) {
                String crossType = node.getCrosstype();
                if (crossType.equals("6") || crossType.equals("7") || crossType.equals("5")) {
                    continue;
                }
                CrossJamTimeHisDay result = new CrossJamTimeHisDay();
                result.setCrossid(node.getCrosscode());
                result.setCrossname(node.getCrossname());
                int congDuration = (int) DetectorService.createDataInRange(120, 0);  // 分钟
                result.setTime(congDuration);
                result.setDate(start);
                result.setGmtcreate(LocalDate.now());
                resultList.add(result);
            }
            crossJamTimeHisDayMapper.insertBatch(resultList);
            start = start.plusDays(1);
        }
    }

    // 创建2021年全年每个月的拥堵时长，统计间隔：月
    public void createCrossJamTimeHisMonthData2(LocalDate start, LocalDate last) {
        while (start.isBefore(last)) {
            List<CrossJamTimeHisMonth> resultList = new ArrayList();
            for (CrossBase node : BaseData.crossBaseList) {
                String crossType = node.getCrosstype();
                if (crossType.equals("6") || crossType.equals("7") || crossType.equals("5")) {
                    continue;
                }
                CrossJamTimeHisMonth result = new CrossJamTimeHisMonth();
                result.setCrossid(node.getCrosscode());
                result.setCrossname(node.getCrossname());
                int congDuration = (int) DetectorService.createDataInRange(1500, 0);  // 分钟
                result.setTime(congDuration);
                result.setDate(start);
                result.setGmtcreate(LocalDate.now());
                resultList.add(result);
            }
            crossJamTimeHisMonthMapper.insertBatch(resultList);
            start = start.plusMonths(1);
        }
    }


    @Scheduled(cron = "0 0 */1 * * ?") // 每小时执行一次
    public void createCrossDeviceDataHis() {
        String crossCode = "crossCode";
        String deviceType = "deviceType";
        String deviceNum = "deviceNum";
        List<Map<String ,String >> crossDevNum = devBaseMapper.getCrossDevNum();
        List<CrossDeviceDataHis> crossDeviceDataHisList = new ArrayList<>();
        for (Map cross:crossDevNum) {
            CrossDeviceDataHis result = new CrossDeviceDataHis();
            result.setUuid(UUID.randomUUID().toString());
            result.setCrossid((String)cross.get(crossCode));
            result.setCrossname(null);
            switch ((String)cross.get(deviceType)) {
                case "01": // 卡口
                    result.setDevicetype("卡口");
                    result.setDatatype("卡口数据类型");
                    break;
                case "02": // 电警
                    result.setDevicetype("电警");
                    result.setDatatype("违法数据类型");
                    break;
                case "03": // 视频检测器
                    result.setDevicetype("视频检测器");
                    result.setDatatype("检测器流量类型");
                    break;
                case "04":
                    result.setDevicetype("诱导屏");
                    result.setDatatype("停车诱导数据类型");
                    break;
                default:
                    result.setDevicetype("其他");
                    result.setDatatype("其他");
                    break;
            }
            int volume_raw = (int)(DetectorService.createDataInRange(2100, 1500) * ((Number)cross.get(deviceNum)).intValue());
            double percentage = DetectorService.createDataInRange(0.99, 0.85);
            int volume_clean = (int)(volume_raw * percentage);
            result.setOriginaldatacount(volume_raw);
            result.setCleandatacount(volume_clean);
            result.setDatestamp(LocalDateTime.now());
            result.setCreator(null);
            result.setGmtcreate(LocalDateTime.now());
            result.setModifier(null);
            result.setGmtmodified(null);
            result.setDatastatus(null);
            result.setVersion(null);
            result.setRemark(null);
            crossDeviceDataHisList.add(result);
        }
        crossDeviceDataHisMapper.insertBatch(crossDeviceDataHisList);
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void createCrossRunningStateRtData() {
        crossRunningStateRtMapper.deleteByExample(null); // 删除所有数据
        List<CrossRunningStateRt> resultList = new ArrayList();
        for (CrossBase node: BaseData.crossBaseList) {
            if (node.getCrosstype().equals("6")  || node.getCrosstype().equals("7") || node.getCrosstype().equals("5")){
                continue;
            }
            CrossRunningStateRt result = new CrossRunningStateRt();
            result.setCrossid(node.getCrosscode());
            result.setCrossname(node.getCrossname());
            int vol = (int)DetectorService.createDataInRange(500, 100);
            double littlePercent = DetectorService.createDataInRange(1, 0.9);
            int littlerCar = (int)(vol * littlePercent);
            int bigCar = vol - littlerCar;
            double avgQueue = vehLen * vol / (4 * interval);
            avgQueue = Math.round(avgQueue);
            double speed = Math.round(DetectorService.createDataInRange(50, 20));
            result.setFlowreal(vol);
            result.setSpeedreal(speed);
            result.setBigcar(bigCar);
            result.setLittlecar(littlerCar);
            result.setQueue(avgQueue);
            result.setGmtcreate(LocalDate.now());
            resultList.add(result);
        }
        crossRunningStateRtMapper.insertBatch(resultList);
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void createCrossJamTimeHisHourData() {
        List<CrossJamTimeHisHour> resultList = new ArrayList();
        for (CrossBase node: BaseData.crossBaseList) {
            String crossType = node.getCrosstype();
            if (crossType.equals("6")  || crossType.equals("7") || crossType.equals("5")){
                continue;
            }
            CrossJamTimeHisHour result = new CrossJamTimeHisHour();
            result.setCrossid(node.getCrosscode());
            result.setCrossname(node.getCrossname());
            int congDuration = (int)DetectorService.createDataInRange(20, 0);  // 分钟
            result.setTime(congDuration);
            result.setDatetime(LocalDateTime.now());
            result.setGmtcreate(LocalDate.now());
            resultList.add(result);
        }
        crossJamTimeHisHourMapper.insertBatch(resultList);
    }

    @Scheduled(cron = "0 0 0 0/1 * ?")
    public void createCrossJamTimeHisDayData() {
        List<CrossJamTimeHisDay> resultList = new ArrayList();
        for (CrossBase node: BaseData.crossBaseList) {
            String crossType = node.getCrosstype();
            if (crossType.equals("6")  || crossType.equals("7") || crossType.equals("5")){
                continue;
            }
            CrossJamTimeHisDay result = new CrossJamTimeHisDay();
            result.setCrossid(node.getCrosscode());
            result.setCrossname(node.getCrossname());
            int congDuration = (int)DetectorService.createDataInRange(120, 0);  // 分钟
            result.setTime(congDuration);
            result.setDate(LocalDate.now());
            result.setGmtcreate(LocalDate.now());
            resultList.add(result);
        }
        crossJamTimeHisDayMapper.insertBatch(resultList);
    }

    @Scheduled(cron = "0 1 0 1 */1 ?")
    public void createCrossJamTimeHisMonthData() {
        List<CrossJamTimeHisMonth> resultList = new ArrayList();
        for (CrossBase node: BaseData.crossBaseList) {
            String crossType = node.getCrosstype();
            if (crossType.equals("6")  || crossType.equals("7") || crossType.equals("5")){
                continue;
            }
            CrossJamTimeHisMonth result = new CrossJamTimeHisMonth();
            result.setCrossid(node.getCrosscode());
            result.setCrossname(node.getCrossname());
            int congDuration = (int)DetectorService.createDataInRange(1500, 0);  // 分钟
            result.setTime(congDuration);
            result.setDate(LocalDate.now());
            result.setGmtcreate(LocalDate.now());
            resultList.add(result);
        }
        crossJamTimeHisMonthMapper.insertBatch(resultList);
    }

}
